﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Runda.EShop.Bll;
using System.Data;
using Runda.EShop.Common.Entity;
using Runda.EShop.Common.Component;
using Runda.EShop.Common.Utility;

namespace Runda.EShop.Web.Customer
{
    public partial class Shopcart : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindShopcart();

                if (base.User.Identity.LoginUser.EntType == (int)EnumHelper.EnterpriseType.Agent)
                {
                    gvList.Columns[3].Visible = false;
                    gvList.Columns[4].Visible = false;
                    gvList.Columns[5].Visible = false;
                }
            }
        }

        private void BindShopcart()
        {
            CustomerBll bll = new CustomerBll();
            DataTable dt = bll.GetMyShopcart(base.User.Identity.LoginUser.UserID);
            gvList.DataSource = dt;
            gvList.DataBind();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            BizShopCartBll bll = new BizShopCartBll();
            //检查该企业是否过期
            BizEnterpriseEntity ent = bll.Get<BizEnterpriseEntity>(base.User.Identity.LoginUser.EntID);
            if (ent != null && !ent.Expired)
            {

            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "error1", "alert('注册证已到期，请联系管理员');", true);
                return;
            }

            List<BizShopCartEntity> list = new List<BizShopCartEntity>();
            BizShopCartEntity entity = null;
            bool flag = true;
            //当库存数量不为零时，订购数量不能大于库存数量
            bool IsGreaterStock = true;

            foreach (GridViewRow row in gvList.Rows)
            {
                DecimalTextBox txtQuantity = row.FindControl("txtQuantity") as DecimalTextBox;
                Label lblInventory = row.FindControl("lblInventory") as Label;
                Label lblUnit = row.FindControl("lblUnit") as Label;
                if ((!txtQuantity.Value.HasValue) || txtQuantity.Value.Value <= 0)
                {
                    flag = false;
                    break;
                }
                if (base.User.Identity.LoginUser.EntType == (int)EnumHelper.EnterpriseType.Terminal)
                {
                    decimal Inventory = 0;
                    decimal.TryParse(lblInventory.Text.Trim(), out Inventory);

                    if (Inventory != 0 && Inventory < txtQuantity.Value.Value)
                    {
                        IsGreaterStock = false;
                        break;
                    }
                }
                DropDownList ddlUnit = row.FindControl("ddlUnit") as DropDownList;
                TextBox txtRemark = row.FindControl("txtRemark") as TextBox;
                Guid CartID = new Guid(gvList.DataKeys[row.RowIndex]["CartID"].ToString());
                entity = new BizShopCartEntity(CartID);
                entity.ProductID = new Guid(gvList.DataKeys[row.DataItemIndex]["ProductID"].ToString());
                entity.CustomerID = base.User.Identity.LoginUser.UserID;
                entity.Quantity = txtQuantity.Value.Value;
                entity.DueDate = DateTime.Now;
                entity.CreatedAt = DateTime.Now;
                entity.Unit = lblUnit.Text;//ddlUnit.SelectedValue;
                entity.Remark = txtRemark.Text;
                list.Add(entity);
            }

            if (!flag)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "error", "alert('请输入定货数量且大于零!');", true);
                return;
            } 
            
            if (!IsGreaterStock)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "error", "alert('订购数量不能大于库存数量!');", true);
                return;
            }

            //判断是否存在同产品的空订单未发货
            BizShopCartBll existsbll = new BizShopCartBll();
            BasProductEntity EntityProd=null;
            bool exists = false;
            foreach (BizShopCartEntity item in list)
            {
                exists = existsbll.ExistsOrderDetail(base.User.Identity.LoginUser.UserID, item.ProductID);
                if (exists)
                {
                    EntityProd = new BasProductBll().Get<BasProductEntity>(item.ProductID);
                    break;
                }
            }
            if (exists)
            {
                Memo.Text = "您下定的货物:" + EntityProd.ProductCode  + "正在补货（已下定），点击'确认下订'继续下单，点击'取消'将取消订单。";
                //ClientScript.RegisterStartupScript(this.GetType(), "error", "alert('同时下定时自动判断下单品项是否还有历史订单未交，提示客户确认是否下单或返回修改购物车。!');", true);
                pnlGO.Visible = true;
                Panel1.Visible = false;
                return;
            }
            //CustomerBll bll = new CustomerBll();
            //bll.ModifyShopcart(list);
            bll.BatchUpdate(list);

            Response.RedirectPermanent("OrderAddr.aspx");
        }

        protected void gvList_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            Guid CartID = new Guid(gvList.DataKeys[e.RowIndex]["CartID"].ToString());

            CustomerBll bll = new CustomerBll();
            bll.Delete<BizShopCartEntity>(" and CartID = '"+CartID+"'");

            BindShopcart();
        }

        protected void gvList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataRowView dv = e.Row.DataItem as DataRowView;
                //DropDownList ddlUnit = e.Row.FindControl("ddlUnit") as DropDownList;
                //ddlUnit.SelectedValue = dv["Unit"].ToString();

                ImageButton btnDelete = e.Row.FindControl("btnDelete") as ImageButton;
                btnDelete.Attributes.Add("onclick", "return confirm('确认要删除吗？');");
            }
        }

        protected void lnkbtnOK_Click(object sender, EventArgs e)
        {
            BizShopCartBll bll = new BizShopCartBll();
            //检查该企业是否过期
            BizEnterpriseEntity ent = bll.Get<BizEnterpriseEntity>(base.User.Identity.LoginUser.EntID);
            if (ent != null && !ent.Expired)
            {

            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "error1", "alert('注册证已到期，请联系管理员');", true);
                return;
            }

            List<BizShopCartEntity> list = new List<BizShopCartEntity>();
            BizShopCartEntity entity = null;
      
            foreach (GridViewRow row in gvList.Rows)
            {
                DecimalTextBox txtQuantity = row.FindControl("txtQuantity") as DecimalTextBox;
                Label lblInventory = row.FindControl("lblInventory") as Label;
                Label lblUnit = row.FindControl("lblUnit") as Label;
               
                DropDownList ddlUnit = row.FindControl("ddlUnit") as DropDownList;
                TextBox txtRemark = row.FindControl("txtRemark") as TextBox;
                Guid CartID = new Guid(gvList.DataKeys[row.RowIndex]["CartID"].ToString());
                entity = new BizShopCartEntity(CartID);
                entity.CustomerID = base.User.Identity.LoginUser.UserID;
                entity.Quantity = txtQuantity.Value.Value;
                entity.DueDate = DateTime.Now;
                entity.CreatedAt = DateTime.Now;
                entity.Unit = lblUnit.Text;//ddlUnit.SelectedValue;
                entity.Remark = txtRemark.Text;
                list.Add(entity);
            }
            bll.BatchUpdate(list);

            Response.RedirectPermanent("OrderAddr.aspx");
        }

        protected void lnkbtnCancel_Click(object sender, EventArgs e)
        {
            pnlGO.Visible = false;
            Panel1.Visible = true;
        }
    }
}